<template>
  <div class="component_container">
    <!-- 机构选择组件 -->
    <el-tooltip
      :content="displayOrgName"
      :disabled="!displayOrgName || displayOrgName.length < 10"
      placement="top"
    >
      <el-input
        v-model="displayOrgName"
        placeholder="选择机构"
        :size="size"
        clearable
        readonly
        @click="openDialog"
      >
        <template v-if="displayOrgName" #suffix>
          <circle-close class="icon clear_icon" @click="clearInfo" />
        </template>
      </el-input>
    </el-tooltip>

    <!-- 选择机构弹框 -->
    <el-dialog
      v-model="visible"
      title="选择机构"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="10vh"
      center
      width="1000px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="search_bar">
          <div class="left_search">
            <div class="filter_item">
              <div class="label">机构名称：</div>
              <el-input
                v-model="filterData.orgName"
                size="small"
                placeholder="请输入"
                clearable
              ></el-input>
            </div>

            <div class="filter_item">
              <div class="label">机构状态：</div>
              <el-select
                v-model="filterData.orgStatus"
                placeholder="请选择"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in prepareData.orgStatusSelectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>

            <div class="filter_item">
              <div class="label">是否可加入：</div>
              <el-select
                v-model="filterData.canJoin"
                placeholder="请选择"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in prepareData.canJoinSelectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>

            <!-- <div class="filter_item">
            <div class="label">机构管理员：</div>
            <el-select
              v-model="filterData.orgManagerId"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.canJoinSelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div> -->
          </div>
          <div class="right_search">
            <el-button-group>
              <el-button
                size="small"
                :loading="tableLoading"
                type="primary"
                @click="handleSearch"
              >
                搜索
              </el-button>
              <el-button size="small" @click="handleReset"> 重置 </el-button>
            </el-button-group>
          </div>
        </div>

        <div class="table_box f_1">
          <vxe-table
            v-loading="tableLoading"
            :data="tableData"
            :sort-config="{ remote: true }"
            :radio-config="{ highlight: true }"
            :row-config="{ height: 100 }"
            ref="xTable"
            resizable
            align="center"
            border
            height="100%"
            show-overflow="tooltip"
            highlight-hover-row
            highlight-current-row
            class="xTable"
            @radio-change="handleRadioChange"
          >
            <vxe-column type="radio" width="60" fixed="left">
              <template #header>
                <div>
                  <el-button
                    type="text"
                    :disabled="!tableSelectRow"
                    @click="clearRadioRow"
                  >
                    取消
                  </el-button>
                </div>
              </template>
            </vxe-column>

            <vxe-column
              type="seq"
              title="序号"
              width="60"
              fixed="left"
            ></vxe-column>
            <TableColum :colums="tableColum">
              <template #avatar="{ props }">
                <div style="text-align: center">
                  <div
                    v-if="props.row.avatarUrl"
                    @click.stop=""
                    class="d_f j_c"
                  >
                    <el-image
                      style="width: 80px; height: 80px; border-radius: 50%"
                      :src="props.row.avatarUrl"
                      :preview-src-list="[props.row.avatarUrl]"
                      lazy
                    ></el-image>
                  </div>
                  <span v-else>无</span>
                </div>
              </template>
            </TableColum>
          </vxe-table>
        </div>
        <el-pagination
          v-model="pagenationData.current"
          :page-sizes="[500, 100, 50, 15]"
          :page-size="pagenationData.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagenationData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
          style="text-align: center; margin-top: 10px"
        >
        </el-pagination>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="dialogLoading"
            size="small"
          >
            选择
          </el-button>
          <el-button @click="closeDialog" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  computed,
  getCurrentInstance,
  toRefs,
  watch,
} from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { dealImgUrl } from "../utils/common";
import { debounce } from "lodash";
import TableColum from "./TabelTemplate/TableColum.vue";

const initFilterData = () => {
  return {
    orgName: null,
    orgStatus: "1",
    canJoin: "1",
  };
};

export default {
  name: "OrgSelect",
  components: {
    TableColum,
  },
  props: {
    size: {
      type: String,
      default: "small",
      validator: (val) => {
        return ["mini", "small", "default", "large"].includes(val);
      },
    },
    defaultOrgName: {
      type: String,
      default: "",
    },
    modelValue: Number,
  },
  emits: ["update:modelValue", "confirm"],
  setup(props, context) {
    // ------------------ 通用属性 start --------------------
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();
    // ------------------ 通用属性 end ----------------------

    /**
     * 计算属性
     */
    const userInfo = computed(() => store.state.user.userInfo);

    // 选择框显示的机构名称
    const displayOrgName = ref("");

    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});

    // 预加载数据
    const prepareData = reactive({
      orgStatusSelectList: [],
      canJoinSelectList: [],
    });

    const tableState = reactive({
      xTable: null,
      tableData: [],
      tableLoading: false,
      tableColum: {
        orgName: {
          title: "机构名称",
          props: { sortable: false },
        },
        orgAvatar: {
          title: "机构logo",
          props: { sortable: false },
          slotContent: "avatar",
        },
        orgDesc: {
          title: "机构描述",
          props: { sortable: false },
        },
        orgStatusLabel: {
          title: "机构状态",
          props: { sortable: false },
        },
        canJoinLabel: {
          title: "是否可加入",
          props: { sortable: false },
        },
        orgManagerName: {
          title: "机构管理员",
          props: { sortable: false },
        },
        creatorName: {
          title: "创建人",
          props: { sortable: false },
        },
        createdTime: {
          title: "创建时间",
          props: { sortable: false, width: 160 },
        },
      },
      tableSelectRow: null,
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置数据
    const handleResetData = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
    };

    // 重置
    const handleReset = () => {
      handleResetData();
      getTableData();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      $api.organization
        .listPage({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              avatarUrl: dealImgUrl(item.orgAvatar),
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 列表单选选中
    const handleRadioChange = ({ row }) => {
      tableState.tableSelectRow = row;
    };

    // 清除列表选中
    const clearRadioRow = () => {
      tableState.tableSelectRow = null;
      tableState.xTable && tableState.xTable.clearRadioRow();
    };

    // 输入框聚焦
    const orgNameRef = ref(null);
    const focusInput = (refKey) => {
      switch (refKey) {
        case "orgNameRef":
          orgNameRef.value && orgNameRef.value.focus();
          break;
      }
    };

    // 防抖
    const debounceSearch = debounce(handleSearch, 800);

    // 保存
    const handleConfirm = () => {
      if (!tableState.tableSelectRow) {
        return ElMessage.warning("请先选择机构再点击确定");
      }
      const info = {
        orgId: tableState.tableSelectRow.id,
        orgName: tableState.tableSelectRow.orgName,
      };
      displayOrgName.value = info.orgName;
      context.emit("update:modelValue", info.orgId);
      context.emit("confirm", info);
      closeDialog();
    };

    // 打开弹框
    const openDialog = () => {
      handleSearch();
      visible.value = true;
    };

    // 关闭弹框
    const closeDialog = () => {
      console.log(1111);
      // if (dialogLoading.value) {
      //   return;
      // }
      // handleResetData();
      visible.value = false;
    };

    const clearInfo = () => {
      clearRadioRow();
      const info = {
        orgId: null,
        orgName: null,
      };
      displayOrgName.value = info.orgName;
      context.emit("update:modelValue", info.orgId);
      context.emit("confirm", info);
    };

    // 查询预加载数据
    const getPreparedData = () => {
      $api.organization
        .preparedData()
        .then((res) => {
          Object.keys(prepareData).forEach((key) => {
            prepareData[key] = res.data[key] || [];
          });
        })
        .catch((err) => {
          console.error("getPreparedData error: ", err);
        })
        .finally(() => {});
    };

    watch(
      () => props.defaultOrgName,
      (newVal) => {
        // 这里有个大坑，无法监听到改变，只能监听到第一次的改变
        console.log("defaultOrgName=", newVal);
        displayOrgName.value = newVal;
      },
      { immediate: true, deep: true }
    );

    /**
     * 初始化
     */
    getPreparedData();

    return {
      userInfo,
      visible,
      openDialog,
      closeDialog,
      dialogLoading,
      handleConfirm,
      filterData,
      prepareData,
      pagenationData,
      handleSearch,
      handleReset,
      getTableData,
      handleSizeChange,
      handleCurrentChange,
      handleRadioChange,
      clearRadioRow,
      debounceSearch,
      focusInput,
      orgNameRef,
      clearInfo,
      displayOrgName,
      ...toRefs(tableState),
    };
  },
};
</script>

<style lang="less" scoped>
.component_container {
}

.dialog_container {
  height: calc(92vh - 240px);
  display: flex;
  flex-direction: column;
  .search_bar {
    margin-bottom: 15px;
    justify-content: center;
    .search_box {
      width: 80%;
    }
  }
}

.clear_icon {
  transform: translateY(2px);
  cursor: pointer;
  color: #ccc;
}
</style>
